package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.constant.LyConstants;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SendMsgUtils {

    @Autowired
    private IAcsClient client;

    @Autowired
    private SmsProperties prop;

    /**
     * 发送验证码类对象
     * @param phone 发给谁
     * @param code 验证码
     */
    public void sendCheckCodeMsg(String phone, String code){
        log.info("【阿里云短信】验证码短信开始！");
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(prop.getDomain());
        request.setVersion(prop.getVersion());
        request.setAction(prop.getAction());
        request.putQueryParameter(LyConstants.SMS_PARAM_KEY_REGION_ID, prop.getRegionID());
        request.putQueryParameter(LyConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(LyConstants.SMS_PARAM_KEY_SIGN_NAME, prop.getSignName());
        request.putQueryParameter(LyConstants.SMS_PARAM_KEY_TEMPLATE_CODE, prop.getVerifyCodeTemplate());
        request.putQueryParameter(LyConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\"checkcode\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            Map<String, String> repsMap = JsonUtils.toMap(response.getData(), String.class, String.class);
            if(StringUtils.equals(repsMap.get(LyConstants.SMS_RESPONSE_KEY_CODE), "OK")){
                log.info("【阿里云短信】验证码短信成功结束！用户："+phone+"已经接收到了验证码！");
            }else {
                log.error("【阿里云短信】验证码短信异常！异常信息为："+repsMap.get(LyConstants.SMS_RESPONSE_KEY_MESSAGE));
            }
        } catch (ServerException e) {
            log.error("【阿里云短信】验证码短信阿里云服务器异常！");
            e.printStackTrace();
        } catch (ClientException e) {
            log.error("【阿里云短信】验证码短信本地服务器异常！");
            e.printStackTrace();
        }
    }

}
